var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors')
const router = require('./routes')
const mongoose = require('./utils/db')
const {maxFileSize} = require('./config')
var app = express();
app.use(cors({
  "origin": true, //true 设置为 req.origin.url
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", //容许跨域的请求方式
  "allowedHeaders": "x-requested-with,Authorization,token, content-type", //跨域请求头
  "preflightContinue": false, // 是否通过next() 传递options请求 给后续中间件
  "maxAge": 1728000, //options预验结果缓存时间 20天
  "credentials": true, //携带cookie跨域
  "optionsSuccessStatus": 200 //options 请求返回状态码
}))

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'uploads')));

// 挂载路由
app.use(router)


app.use(function (req, res, next) {
  next(createError(404));
});

const ERROR_CODE_MAP = {
  'LIMIT_FILE_SIZE': `文件大小不得超过 ${maxFileSize} bytes`,

}
const ERROR_STATUS_MAP = {
  '401': "无权限操作,请先登录"
}
const QUE_MAP = {
  "username": "用户名",
  "password": "密码",
  "email": "邮箱"
}
// error handler
app.use(function (err, req, res, next) {
  let message = err.message
  if (message.indexOf('validation failed') !== -1) {
    var arr = Object.keys(QUE_MAP)
    for (const item of arr) {
      if (message.indexOf(item) !== -1) {
        message = message.split(item)[1]
        break;
      }
    }
    err.status = 422
  }
  if (err.code in ERROR_CODE_MAP) {
    err.status = 422
    message = ERROR_CODE_MAP[err.code]
  }

  if (err.status in ERROR_STATUS_MAP) {
    message = ERROR_STATUS_MAP[err.status]
  }
  res.status(err.status || 500).json({ // err对象属性属于原型上的成员，而json只能将对象本身的成员序列化到字符串
    code: err.status || 500,
    message: message || '错误'
  })
});

module.exports = app;
